package juc;

import org.junit.Test;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <pre>类名: SemaphoneTest</pre>
 * <pre>描述: 信号量测试</pre>
 * <pre>版权: web_chen@163.com</pre>
 * <pre>日期: 2020/11/6 8:55</pre>
 * <pre>作者: chenwb</pre>
 */
public class SemaphoneTest {

	/**
	 * 实现一个同时只能处理5个请求的限流器
	 */
	private Semaphore semaphore = new Semaphore(5);

	/**
	 * 定义一个线程池
	 */
	private ThreadPoolExecutor executor = new ThreadPoolExecutor(20, 50, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>(2000));

	/**
	 * 模拟执行方法
	 */
	public void exec() {
		try {
			semaphore.acquire(1);
			// 模拟真实方法执行
			System.out.println("执行exec方法,时间：" + System.currentTimeMillis());
			Thread.sleep(1000);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			semaphore.release(1);
		}
	}

	@Test
	public void test() throws InterruptedException {
		for (; ; ) {
			Thread.sleep(100);
			// 模拟请求以10个/s的速度
			executor.execute(() -> exec());
		}
	}
}
